package com.example.swimmingpool.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.example.swimmingpool.SwimmingPoolThreadLocal;
import com.example.swimmingpool.constants.RedisConstants;
import com.example.swimmingpool.response.CommonResponse;
import com.example.swimmingpool.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class SwimmingPoolInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        var token = request.getHeader("token");
        var key = RedisConstants.SWIMMING_USER + token;
        var s = redisUtil.get(key);
        if (StrUtil.isBlank(s)) {
            var res = CommonResponse.fail("登录过期");
            response.getWriter().print(JSON.toJSONString(res));
            return false;
        }
        redisUtil.getRedis().expire(key,Duration.ofDays(RedisConstants.SWIMMING_USER_EXPIRE));
        SwimmingPoolThreadLocal.putUserId(Long.valueOf(s));
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) throws Exception {
        SwimmingPoolThreadLocal.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
